<?php

class ObjectlinkController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','subviewedit','subviewload','printqvobject'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
        
        public function actionSubViewEdit()
	{
                if(isset($_POST['Objectlink']['objectlink_id'])){
                    if(0==$_POST['Objectlink']['objectlink_id'] OR ""==$_POST['Objectlink']['objectlink_id']){
                        $model = new Objectlink();
                    }else{
                        $model=$this->loadModel($_POST['Objectlink']['objectlink_id']);
                    }
                }else{
                    $model = new Objectlink();
                }

                // Uncomment the following line if AJAX validation is needed
		//$this->performAjaxValidation($model);

		if(isset($_POST['Objectlink']))
		{
			$model->attributes=$_POST['Objectlink'];
			$model->save();
                        
                        $res = array(
                            'objectlink_id'=>$model->objectlink_id,
                            'org_id'=>$model->org_id,
                            'nachname'=>$model->org->nachname,
                            'object_id'=>$model->object_id
                        );
                        
                        echo CJSON::encode($res);
		}                                

	}
        
        public function actionSubViewLoad($id)
	{

                $criteria=new CDbCriteria(
                    array(
                        'condition'=>'objectlink_id = '.$id,
                        'with'=> array('org'),
                ));

                $model=  Objectlink::model()->find($criteria);

                $res = array(
                    'objectlink_id'=>$model->objectlink_id,
                    'org_id'=>$model->org_id,
                    'nachname'=>$model->org->nachname,
                    'object_id'=>$model->object_id
                );

                echo CJSON::encode($res);

	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Objectlink;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Objectlink']))
		{
			$model->attributes=$_POST['Objectlink'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->objectlink_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Objectlink']))
		{
			$model->attributes=$_POST['Objectlink'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->objectlink_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
                        //we need to delete the related filters first, otherwise i get an error
                        ObjectQvfilters::model()->deleteAll('objectlink_id = :objectlink_id',array(':objectlink_id'=>$id));
                     
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Objectlink');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Objectlink('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Objectlink']))
			$model->attributes=$_GET['Objectlink'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Objectlink::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='objectlink-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionprintQvObject(){
            if(isset($_GET['id'])){
                $id = $_GET['id'];
                $date = $_GET['date'];   
                try {
                    ini_set('soap.wsdl_cache_enabled',1);

                    $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
                    $client->soap_defentcoding='UTF-8';

                    $ObjRequest = $this->buildBeeyeParameter($id, $date);

                    $SOAPResponse = $client->PrintbeeyeQvObject($ObjRequest);
                    $bmpURL = $SOAPResponse->PrintbeeyeQvObjectResult;

                    //if all parameters are correct, we will have the image inside the url - be careful that the webserver needs access to the folder, otherwise the following functions would not work
                    //$browserimage = $this->imagecreatefrombmp($bmpURL);

                    header("Content-Type: image/bmp");
                    header("Content-Transfer-Encoding: binary\n");
                    //imagegif($browserimage);
                    //imagedestroy($browserimage);
                    
//                    while(!file_exists($bmpURL)){
//                            "";
//                    }
                    
                    readfile($bmpURL);
                  
                }catch (Exception $exc) {
                    print_r($exc->getTraceAsString());
                }
                exit;
            }
        }
        
        
        public function buildBeeyeParameter($id,$date){
            $target_encoding = "UTF-8";
            $objectlink = $this->loadModel($id);
            
            $ReportObject = Objects::model()->findByPk($objectlink->object_id)->with('qvo');
            

            $doc = new beeyeQvObject();
            $doc->ObjectID = $id;
            $doc->DocName = $ReportObject->qvo->qvo_docName;
            $doc->ObjectName=$ReportObject->qvo->qvo_objectName;
            $doc->SheetName=$ReportObject->qvo->qvo_sheetNumber;
            $doc->RefreshType=$ReportObject->type;
            $doc->RefreshFormat=$ReportObject->s_format;
            $doc->RefreshDay=$ReportObject->s_zyklus_start;
            
            $ObjRequest = new PrintbeeyeQvObject();
            $ObjRequest->_docName = $ReportObject->qvo->qvo_docName;

            //the filter
            $Filters=array();
            $MyFilters = ObjectQvfilters::model()->with('qvf')->findAll('objectlink_id = :objectlink_id',array(':objectlink_id'=>$objectlink->objectlink_id));
            if(count($MyFilters)>=1){
                foreach($MyFilters AS $MyFilter){
                     $Filters[] = $this->beeyeConditionCleaner($MyFilter->filter,Qvfields::model()->findByPK($MyFilter->qvf_id)->qvf_fieldName);
                }
                $ObjRequest->_fieldSelection = $Filters;
            }else{
                $ObjRequest->_fieldSelection = "";
            }                              
                        
            $ObjRequest->_objectName = $doc;            
            return $ObjRequest;
    }
    
    private function beeyeConditionCleaner($Condidtion,$FieldName){
        //inititilisieren der filter
        $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
        $newvalues = array();
        if(preg_match("/\,/",$Condidtion)){
            $values = preg_split("/\,/",$Condidtion);
            foreach($values AS $value){
                if($value != ''){
                    $beeyeQvValue = new beeyeQvValue();
                    $beeyeQvValue->FieldName = $FieldName;
                    $beeyeQvValue->FieldValue = trim($value);                   
                    $newvalues[]=$beeyeQvValue;
                }
            }
        }else{
            $beeyeQvValue = new beeyeQvValue();
            $beeyeQvValue->FieldName = $FieldName;
            $beeyeQvValue->FieldValue = trim($Condidtion);                   
            $newvalues[]=$beeyeQvValue;
        }
        $Filter = new beeyeQvFieldSelection();
        $Filter->FieldName = $FieldName;
        $Filter->FieldValues=$newvalues;
        return $Filter;
    }
    
    private function beeyeDynConditionCleaner($Condidtion){
            //zerlegen des ausdrucks in die einzelteile
            $filterlines = explode(";",$Condidtion);
            //var_dump($filterlines);
            foreach($filterlines as $filterline){
                if(preg_match("/\=/",$filterline)){
                    $conditions = explode("=",$filterline);
                    //var_dump($conditions);
                    $value = $conditions[1];
                    //inititilisieren der filter
                    $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
                    $newvalues = array();
                    if(preg_match("/\,/",$value)){
                        $values = preg_split("/\,/",$value);
                        foreach($values AS $ffvalue){
                            if($ffvalue != ''){
                                $beeyeQvValue = new beeyeQvValue();
                                $beeyeQvValue->FieldName = $conditions[0];
                                $beeyeQvValue->FieldValue = trim($ffvalue);                   
                                $newvalues[]=$beeyeQvValue;
                            }
                        }
                    }else{
                        $beeyeQvValue = new beeyeQvValue();
                        $beeyeQvValue->FieldName = $conditions[0];
                        $beeyeQvValue->FieldValue = trim($value);                   
                        $newvalues[]=$beeyeQvValue;
                    }

                    $Filters = new beeyeQvFieldSelection();
                    $Filters->FieldName = $conditions[0];
                    $Filters->FieldValues=$newvalues;

                    $Filter[]=$Filters;
                }
            }
                        
            return $Filter;
        }
}
